/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controller.user;

import dao.IphoneDAO;
import dao.IpodDAO;
import dao.OrdersIphoneDAO;
import dao.OrdersIpodDAO;
import dao.UsersDAO;
import entity.Ordersiphone;
import entity.Ordersipod;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Turtle
 */
public class cart extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet cart</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet cart at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        String action = request.getParameter("action");
        String url = "";

        if (session.getAttribute("user") == null || !session.getAttribute("user").equals("normal")) {
            response.sendRedirect("login?action=load");
            return;
        }

        if (action == null) {
            url = "userpages/cart.jsp";
        } else if (action.equals("load")) {
            ArrayList<String> proList = new ArrayList<String>();
            ArrayList<String> proName = new ArrayList<String>();

            if (session.getAttribute("cart") != null) {
                proList = (ArrayList<String>) session.getAttribute("cart");
            }

            for (int i = 0; i < proList.size(); i++) {
                if (proList.get(i).contains("IPH")) {
                    proName.add(IphoneDAO.getProductByID(proList.get(i)).getName());
                } else {
                    proName.add(IpodDAO.getProductByID(proList.get(i)).getName());
                }
            }

            request.setAttribute("proList", proList);
            request.setAttribute("proName", proName);

            url = "userpages/cart.jsp";
        } else if (action.equals("confirm")) {
            if (request.getParameter("recaptcha_challenge_field") != null && request.getParameter("recaptcha_response_field") != null) {
                String remoteAddr = request.getRemoteAddr();
                net.tanesha.recaptcha.ReCaptchaImpl reCaptcha = new net.tanesha.recaptcha.ReCaptchaImpl();
                reCaptcha.setPrivateKey("6LcUpMgSAAAAADvB3WhgJac8hmj1hVk7rvSY-72F");

                String challenge = request.getParameter("recaptcha_challenge_field");
                String uresponse = request.getParameter("recaptcha_response_field");
                net.tanesha.recaptcha.ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);

                if (reCaptchaResponse.isValid()) {
                    ArrayList<String> cart = (ArrayList<String>) session.getAttribute("cart");

                    boolean mark = false;

                    if (cart != null) {
                        for (int i = 0; i < cart.size(); i++) {
                            if (cart.contains("IPH")) {
                                Ordersiphone order = new Ordersiphone();

                                order.setAmount(1);
                                order.setEmail(UsersDAO.getUserInfo((String) session.getAttribute("user_name")).getEmail());
                                order.setFullName((String) session.getAttribute("user_name"));
                                order.setOrdersDate(new Date());
                                order.setProductId(cart.get(i));

                                if (OrdersIphoneDAO.insertOrder(order)) {
                                    mark = true;
                                    url = "shopresult?action=load";
                                } else {
                                    mark = false;
                                    request.setAttribute("error_info", "Fail to commit. Please check again or re-log in your account.");
                                    url = "userpages/cart.jsp";
                                }
                            } else {
                                Ordersipod order = new Ordersipod();

                                order.setAmount(1);
                                order.setEmail(UsersDAO.getUserInfo((String) session.getAttribute("user_name")).getEmail());
                                order.setFullName((String) session.getAttribute("user_name"));
                                order.setOrdersDate(new Date());
                                order.setProductId(cart.get(i));

                                if (OrdersIpodDAO.insertOrder(order)) {
                                    mark = true;
                                    url = "shopresult?action=load";
                                } else {
                                    mark = false;
                                    request.setAttribute("error_info", "Fail to commit. Please check again or re-log in your account.");
                                    url = "userpages/cart.jsp";
                                }
                            }
                        }
                    }

                    if (mark) {
                        session.removeAttribute("cart");
                    }
                } else {
                    request.setAttribute("error_info", "The register code is not valid.");
                    url = "cart?action=load";
                }
            }
        }

        RequestDispatcher rd = request.getRequestDispatcher(url);
        rd.forward(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
